<?php

namespace app\admin\model\kuerp;

use app\admin\model\Admin;
use think\Db;
use think\Log;
use think\Model;


class GoodsSales extends Model
{

    // 表名
    protected $name = 'kuerp_goods_sales';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'purchase_type_text',
        'purchase_time_text',
        'delivery_time_text',
        'pay_status_text',
        'check_status_text',
        'examine_status_text',
        'examine_time_text'
    ];
    

    
    public function getPurchaseTypeList()
    {
        return ['1' => __('Purchase_type 1'), '2' => __('Purchase_type 2')];
    }

    public function getPayStatusList()
    {
        return ['0' => __('Pay_status 0'), '1' => __('Pay_status 1'), '2' => __('Pay_status 2')];
    }

    public function getCheckStatusList()
    {
        return ['0' => __('Check_status 0'), '1' => __('Check_status 1')];
    }

    public function getExamineStatusList()
    {
        return ['0' => __('Examine_status 0'), '1' => __('Examine_status 1'), '2' => __('Examine_status 2')];
    }


    public function getPurchaseTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['purchase_type']) ? $data['purchase_type'] : '');
        $list = $this->getPurchaseTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getPurchaseTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['purchase_time']) ? $data['purchase_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getDeliveryTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['delivery_time']) ? $data['delivery_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getPayStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['pay_status']) ? $data['pay_status'] : '');
        $list = $this->getPayStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getCheckStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['check_status']) ? $data['check_status'] : '');
        $list = $this->getCheckStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getExamineStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['examine_status']) ? $data['examine_status'] : '');
        $list = $this->getExamineStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getExamineTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['examine_time']) ? $data['examine_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setPurchaseTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setDeliveryTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setExamineTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }


    public function customers()
    {
        return $this->belongsTo('Customers', 'customers_id', 'id', [], 'LEFT')
            ->field('id,customer_name,connet_name,customer_mobile,staff_member_id')
            ->setEagerlyType(0);
    }

    public function getStoresList(){
        return (new Stores())->where(['status'=>1])->select();
    }
    public function getSuppliersList(){
        return (new Suppliers())->where(['status'=>1])->select();
    }
    public function getExpendTypeList(){
        return (new ExpendType())->where(['status'=>1])->select();
    }
    public function getGoodsList(){
        return (new Goods())->where(['status'=>1])->select();
    }
    public function getAdminList(){
        return Admin::all();
    }
    public function getAccountsList(){
        return (new Accounts())->where(['status'=>1])->select();
    }
    public function getSaleList(){
        return (new StaffMember())->where(['status'=>1])->select();
    }
    public function getCustomersList(){
        return (new Customers())->where(['status'=>1])->select();
    }
    public function getStaffMemberList(){
        return (new StaffMember())->where(['status'=>1])->select();
    }

    public function preparation()
    {
        return $this->belongsTo('app\admin\model\Admin', 'preparation_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function examine()
    {
        return $this->belongsTo('app\admin\model\Admin', 'examine_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
    public function staffmember()
    {
        return $this->belongsTo('StaffMember', 'sale_user', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    //职员
	public function staff() {
		return $this->belongsTo(StaffMember::class, 'sale_user', 'id')->field('id,name,admin_id');
	}
    public function goodssalesinfo()
    {
        return $this->belongsTo('GoodsSalesInfo', 'purchase_code', 'purchase_code', [], 'LEFT')
            ->field('purchase_code,goods_code,goods_type,number,unit_price,back_money,all_money,remark,period')
            ->setEagerlyType(0);
    }


    public static function updatecaijia($account,$num,$type,$purchase_code){  //$account账号 $num续费数量 $type续费类型 1材价通,2询价条数，3网络锁
        $time = time();
        $result = false;
        $caijiaUserModel = new \app\common\model\caijiatong\User();
        $caijiaUinfoModel = new \app\common\model\caijiatong\Userinfoadding();
        $caijiaUsModel = new \app\common\model\caijiatong\UserSoftware();
        $caijiaUsbModel = new \app\common\model\caijiatong\UserSoftwareBuylog();
        $caijiaUserModel->startTrans();
        try {
            foreach ($account as $userinfo_key=>$userinfo){
                if($type == 1){
                    $inq = [];
                    //还需要判断用户的到期时间与当前时间比较
                    $userfaxtime      = $time > $userinfo['faxtime'] ? $time : $userinfo['faxtime'];
                    $usergovtime      = $time > $userinfo['govtime'] ? $time : $userinfo['govtime'];
                    $usermixtime      = $time > $userinfo['mixtime'] ? $time : $userinfo['mixtime'];
                    $userwenkutime    = $time > $userinfo['wenkutime'] ? $time : $userinfo['wenkutime'];
                    $userpdxtime      = $time > $userinfo['pdxtime'] ? $time : $userinfo['pdxtime'];
                    $userbidpricetime = $time > $userinfo['bidpricetime'] ? $time : $userinfo['bidpricetime'];

                    $months = intval($num * 12);
                    $newtimefax = strtotime(date('Y-m-d H:i:s', $userfaxtime) . " +{$months} months");
//                    $newtimefax = strtotime(date('Y-m-d H:i:s', $userfaxtime) . " +{$num} years");
                    $newtimegov = strtotime(date('Y-m-d H:i:s', $usergovtime) . " +{$months} months");
                    $newtimemix = strtotime(date('Y-m-d H:i:s', $usermixtime) . " +{$months} months");
                    $newtimewenku = strtotime(date('Y-m-d H:i:s', $userwenkutime) . " +{$months} months");
                    $newtimepdx = strtotime(date('Y-m-d H:i:s', $userpdxtime) . " +{$months} months");
                    $newtimebidprice = strtotime(date('Y-m-d H:i:s', $userbidpricetime) . " +{$months} months");

                    $updatedata = [
                        'faxtime'=>$newtimefax,'mixtime'=>$newtimemix,
                        'govtime'=>$newtimegov, 'pdxtime'=>$newtimepdx,'wenkutime'=>$newtimewenku,
                        'bidpricetime'=>$newtimebidprice,
                    ];

                    $userinfochange = $caijiaUserModel->where('id',$userinfo['id'])->data($updatedata)->update();
                    //市场价
                    $caijiaUinfoModel->insert([
                        'type' => 'fax',
                        'user_id' => $userinfo['id'],
                        'before' => $userinfo['faxtime'],
                        'after' => $newtimefax,
                        'score' => $num * 365,
                        'direction' => 1,
                        'createtime' => time(),
                        'order_type' => 3,
                        'order_no' => $purchase_code['purchase_code'],
                        'memo' => "CRM".$purchase_code['sale_user_name']."开单审核为用户" . $userinfo['username'] . $userinfo['username'] . "增加了市场价服务时间：" . $num . "年----单据编号：".$purchase_code['purchase_code']
                    ]);
                    //信息价
                    $caijiaUinfoModel->insert([
                        'type' => 'gov',
                        'user_id' => $userinfo['id'],
                        'before' => $userinfo['govtime'],
                        'after' => $newtimegov,
                        'score' => $num * 365,
                        'direction' => 1,
                        'createtime' => time(),
                        'order_type' => 3,
                        'order_no' => $purchase_code['purchase_code'],
                        'memo' => "CRM".$purchase_code['sale_user_name']."开单审核为用户" . $userinfo['username'] . $userinfo['username'] . "增加了信息价服务时间：" . $num . "年----单据编号：".$purchase_code['purchase_code']
                    ]);

                    $caijiaUinfoModel->insert([
                        'type' => 'mix',
                        'user_id' => $userinfo['id'],
                        'before' => $userinfo['mixtime'],
                        'after' => $newtimemix,
                        'score' => $num * 365,
                        'direction' => 1,
                        'createtime' => time(),
                        'order_type' => 3,
                        'order_no' => $purchase_code['purchase_code'],
                        'memo' => "CRM".$purchase_code['sale_user_name']."开单审核为用户" . $userinfo['username'] . $userinfo['username'] . "增加了综合价服务时间：" . $num . "年----单据编号：".$purchase_code['purchase_code']
                    ]);

                    $caijiaUinfoModel->insert([
                        'type' => 'pdx',
                        'user_id' => $userinfo['id'],
                        'before' => $userinfo['pdxtime'],
                        'after' => $newtimepdx,
                        'score' => $num * 365,
                        'direction' => 1,
                        'createtime' => time(),
                        'order_type' => 3,
                        'order_no' => $purchase_code['purchase_code'],
                        'memo' => "CRM".$purchase_code['sale_user_name']."开单审核为用户" . $userinfo['username'] . $userinfo['username'] . "增加了配电箱组价服务时间：" . $num . "年----单据编号：".$purchase_code['purchase_code']
                    ]);

                    $caijiaUinfoModel->insert([
                        'type' => 'bidprice',
                        'user_id' => $userinfo['id'],
                        'before' => $userinfo['bidpricetime'],
                        'after' => $newtimebidprice,
                        'score' => $num * 365,
                        'direction' => 1,
                        'createtime' => time(),
                        'order_type' => 3,
                        'order_no' => $purchase_code['purchase_code'],
                        'memo' => "CRM".$purchase_code['sale_user_name']."开单审核为用户" . $userinfo['username'] . "增加了配电箱组价服务时间：" . $num . "年----单据编号：".$purchase_code['purchase_code']
                    ]);
                }else if($type == 2){
                    $oldinquirynum = $userinfo['inquirynum'];
                    $userinquirynum   = $oldinquirynum;
                    $newinquirynum = $userinquirynum + $num;
                    $userinfochange  = $caijiaUserModel->where('id',$userinfo['id'])->data(['inquirynum'=>$newinquirynum])->update();

                    $inq['direction'] = 1;
                    $score = $num;
                    $inq['memo'] = "CRM".$purchase_code['sale_user_name']."开单审核为用户" . $userinfo['username'] . "增加了询价次数：" . $score . "次----单据编号：".$purchase_code['purchase_code'];
                    $inq['type'] = 'inquiry';
                    $inq['user_id'] = (int) $userinfo['id'];
                    $inq['before'] = (int) $oldinquirynum;
                    $inq['after'] = $newinquirynum;
                    $inq['score'] = $score;
                    $inq['createtime']=time();
                    $inq['order_type'] = 3;
                    $inq['order_no'] = $purchase_code['purchase_code'];
                    $caijiaUinfoModel->insert($inq);
                }else if($type == 3){
                    $adddays = $num * 365;
                    $use_software = $caijiaUsModel->where('id',$userinfo['id'])->find();//还需要判断用户的到期时间与当前时间比较
                    $softwaretime_now = $use_software['softwaretime'];
                    $software_tjtime_now = $use_software['software_tjtime'];
                    $software_aztime_now = $use_software['software_aztime'];
                    if($purchase_code['goods_code'] == 'SP005'){ //计价网络锁
                        $softwaretime_befor = $time > $use_software['softwaretime'] ? $time : $use_software['softwaretime'];
                        $softwaretime_now   = strtotime(date('Y-m-d H:i:s', $softwaretime_befor) . " +{$adddays} days");
                        //增加时间
                        $caijiaUsModel->where('id',$userinfo['id'])->update(['softwaretime'=>$softwaretime_now]);

                        $dispatch_type = 'software';
                        $remark = '购买江西2017清单专家计价软件'.$adddays.'天';
                        $res1 = self::curlAppThirdbuyLockTime('software',$use_software['snmcode'],$adddays,$remark);
                        if($res1['code'] != 200){
                            Log::error('计价软件：'.$res1['msg']);
                            throw new \Exception('计价软件：'.$res1['msg']);
                        }
                    }else if($purchase_code['goods_code'] == 'SP016'){ //算量网络锁
                        $software_tjtime_befor = $time > $use_software['software_tjtime'] ? $time : $use_software['software_tjtime'];
                        $software_tjtime_now   = strtotime(date('Y-m-d H:i:s', $software_tjtime_befor) . " +{$adddays} days");
                        //增加时间
                        $caijiaUsModel->where('id',$userinfo['id'])->update(['software_tjtime'=>$software_tjtime_now]);

                        $dispatch_type = 'software_tj';
                        $remark = '购买土建算量(青橙)'.$adddays.'天';
                        $AgentToken = self::GetAgentToken(); //先获取token，再续费（土建算量需要）
                        if($AgentToken['code'] != 1){
                            Log::error('土建算量：'.$AgentToken['msg']);
                            throw new \Exception('土建算量：'.$AgentToken['msg']);
                        }
                        $agenttoken = $AgentToken['data']['token'];
                        $re3 = self::GetAgentTokenxufei($use_software['memberid'],$adddays,$agenttoken);
                        if($re3['code'] != 1){
                            Log::error('土建算量软件：'.$re3['msg']);
                            throw new \Exception('土建算量软件：'.$re3['msg']);
                        }
                    }else if($purchase_code['goods_code'] == 'SP024'){ //安装网络锁
                        $software_aztime_befor = $time > $use_software['software_aztime'] ? $time : $use_software['software_aztime'];
                        $software_aztime_now   = strtotime(date('Y-m-d H:i:s', $software_aztime_befor) . " +{$adddays} days");
                        //增加时间
                        $caijiaUsModel->where('id',$userinfo['id'])->update(['software_aztime'=>$software_aztime_now]);

                        $dispatch_type = 'software_az';
                        $remark = '购买安装算量(鹏业)'.$adddays.'天';
                        $res4 =  self::AddUserxufei($use_software['memberid'],$adddays,1);
                        if($res4['Code'] != 0){
                            Log::error('安装算量软件：'.$res4['Msg']);
                            throw new \Exception('安装算量软件：'.$res4['Msg']);
                        }
                    }

                    $user_softwarelog =[
                        'user_id'=>$userinfo['user_id'],
                        'dispatch_type'=>$dispatch_type,
                        'buyday'=>$adddays,
                        'price'=> 0 ,
                        'type'=>1,
                        'remark'=>'CRM开单----'.$remark,
                        'admin_user'=>0,
                        'createtime'=>time(),
                        'expire_time_jj'=>$softwaretime_now,
                        'expire_time_jjmf'=>$use_software['softwaretime_mf'],
                        'expire_time_tj'=>$software_tjtime_now,
                        'expire_time_az'=>$software_aztime_now,
                    ];
                    //增加续费记录
                    $caijiaUsbModel->insertGetId($user_softwarelog);
                }
            }
            $caijiaUserModel->commit();
        } catch (\Exception $e) {
            Log::error('材价：'.$e->getMessage().'----'.$e->getLine());
            $caijiaUserModel->rollback();
            throw new \Exception($e->getMessage());
        }

        return true;
    }

    public static function curlAppThirdbuyLockTime($type,$snmCode,$buyDay,$remark)
    {
//        $openId = 'owCLF5tf0HSkBJh0gqWxpkzuXQFw';
        // 接口地址
//        $url = 'http://testerp.wisestar.cn:9191/xbgApi/buyVirtualLockTime'; //测试
        $url = 'http://erpapi.wisestar.cn/xbgApi/buyVirtualLockTime'; //正式

        if($type == 'software_jjmf'){
            $softCode =  'ZJ362302'; //江西2017清单专家计价软件【新标杆】ZJ361702   江西2017清单专家计价软件高校版【新标杆】    ZJ362302
        }else if($type == 'software'){
            $softCode =  'ZJ361702'; //江西2017清单专家计价软件【新标杆】ZJ361702   江西2017清单专家计价软件高校版【新标杆】    ZJ362302
        }

        // 请求参数
        $params = [
            'snmCode'=>$snmCode,
            'softCode'=>$softCode,
            'buyDay'=>$buyDay,
            'remark'=>$remark,
        ];

        $appKey = '865497';
//        $userKey = 'xbgab912dbdab312d8aa09e51231552'; // 用户秘钥(测试)
        $userKey = 'xbg457152dbdab312d8aa09e5123890'; // 用户秘钥（正式）
        $random = substr(str_shuffle('12345678901234567890'), 0, 20); // 20位随机字符串
        $date = date('Ymd'); // 当天的yyyyMMdd日期


        $headers = array(
            'Content-Type: application/json',
            'APPKEY: ' . $appKey,
            'RANDOM: ' . $random,
            'TOKEN: ' . md5($random . $date . $userKey)
        );

        // 将参数转换为JSON字符串
        $jsonData = json_encode($params);

        // 创建cURL资源
        $ch = curl_init();

        // 设置请求URL
        curl_setopt($ch, CURLOPT_URL, $url);

        // 设置请求为POST方法
        curl_setopt($ch, CURLOPT_POST, true);

        // 设置请求体
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);

        // 设置请求头
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        // 设置将响应存储到变量而不是直接输出
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        // 执行请求并获取响应
        $response = curl_exec($ch);
        // 关闭cURL资源
        curl_close($ch);
        return json_decode($response,true);
    }

    //安装算量续费接口
    public static function AddUserxufei($memberid,$days,$ispay)
    {
        $url = "http://zjy.mypy.cn/User/Services/VipSvr.assx/ChangeXbgAuthTime?MemberId=".$memberid."&days=".$days."&isPay=".$ispay;

        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

        $response = curl_exec($curl);
        curl_close($curl);
        // 处理响应
        return json_decode($response,true);
    }

    //土建算量登录平台接口
    public static function GetAgentToken()
    {
        $parameters = [
            'username' => '新标杆测试',
            'password' => base64_encode('xbgtest2023')
        ];

        $url = 'http://agent.iqcsoft.com:9001/user/third/login';

        $headers = array(
            'Content-Type: application/json',
        );

        // 将参数转换为JSON字符串
        $jsonData = json_encode($parameters);

        // 创建cURL资源
        $ch = curl_init();

        // 设置请求URL
        curl_setopt($ch, CURLOPT_URL, $url);

        // 设置请求为POST方法
        curl_setopt($ch, CURLOPT_POST, true);

        // 设置请求体
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);

        // 设置请求头
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        // 设置将响应存储到变量而不是直接输出
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        // 执行请求并获取响应
        $response = curl_exec($ch);
        // 关闭cURL资源
        curl_close($ch);
        return json_decode($response,true);
    }

    //土建算量续费接口
    public static function GetAgentTokenxufei($memberid,$days,$agenttoken)
    {

        // 调用青橙续费接口
        $parameters = [
            'code' => 'XBG',
            'module' => 'cqs',
            'lockType' =>  21,
            'days' => $days,
            'moduleNum' => 1,
            'thirdId' => $memberid
        ];

        $url = 'http://agent.iqcsoft.com:9001/write/other';
        $headers = [
            'Content-Type: application/x-www-form-urlencoded',
            'agenttoken: '.$agenttoken
        ];

        // 将参数转换为URL编码的字符串
        $postData = http_build_query($parameters);

        // 创建cURL资源
        $ch = curl_init();

        // 设置请求URL
        curl_setopt($ch, CURLOPT_URL, $url);

        // 设置请求为POST方法
        curl_setopt($ch, CURLOPT_POST, true);

        // 设置请求体
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);

        // 设置请求头
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        // 设置将响应存储到变量而不是直接输出
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        // 执行请求并获取响应
        $response = curl_exec($ch);

        // 关闭cURL资源
        curl_close($ch);

        return json_decode($response, true);

    }
}
